﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Common;
using QuanLyNganHangDe.DAL;
using QuanLyNganHangDe.DAL.Models;
using System.Data.SqlClient;
using System.IO;
namespace QuanLyNganHangDe.GUI.HeThong
{
    public partial class FormThietLapChuoiKetNoi : Form
    {
        public FormThietLapChuoiKetNoi()
        {
            InitializeComponent();
            this.ActiveControl = txtUserName;
        }

        private string ConnectionStringOnGUI
        {
            get
            {
                var connectionString = string.Format("Data Source={0};Initial Catalog={1};User={2};Password={3};MultipleActiveResultSets=True",
                    txtDBServer.Text.Trim(), txtDBName.Text.Trim(), txtUserName.Text, txtPassword.Text);
                return connectionString;
            }
        }

        public static string ReadFileBinary(string fileName)
        {
            try
            {
                var appPath = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
                var configPath = System.IO.Path.Combine(appPath, fileName);
                if (System.IO.File.Exists(configPath) == false)
                    return null;
                using (var sr = new System.IO.StreamReader(configPath))
                {
                    var st = sr.ReadToEnd();
                    var st2 = "";
                    for (int i = 0; i < st.Length; i++)
                        st2 += Convert.ToChar(Convert.ToInt32(st[i]) - 255);
                    sr.Close();
                    return st2;
                }
            }
            catch
            {
                return "";
            }
        }

        public static void WriteFileBinary(string st, string fileName)
        {
            //var appPath = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
            //var configPath = System.IO.Path.Combine(appPath, fileName);
            using (var sw = new System.IO.StreamWriter(fileName))
            {
                var st2 = "";
                for (int i = 0; i < st.Length; i++)
                    st2 += Convert.ToChar(Convert.ToInt32(st[i]) + 255);
                sw.Write(st2);
                sw.Close();
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                //string folderPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                //    "QLNHD");
                string folderPath = txtFolder.Text;
                if (System.IO.Directory.Exists(folderPath) == false)
                {
                    try
                    {
                        System.IO.Directory.CreateDirectory(folderPath);
                    }
                    catch (Exception exc)
                    {
                        DialogUtils.ShowError("Không thể tạo thư mục cho chương trình được.\nChi tiết lỗi: " + exc.Message);
                        return;
                    }
                }
                WriteFileBinary(ConnectionStringOnGUI, folderPath + "\\connect.bin");
                Program.connectionString = FormThietLapChuoiKetNoi.ReadFileBinary(folderPath + "\\connect.bin");
                this.Close();
            }
            catch (Exception exc)
            {
                DialogUtils.ShowMessage("Không lưu được thông tin kết nối! Lỗi " + exc.Message);
            }
        }

        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            try
            {
                SqlConnection tmpConn = new SqlConnection();
                tmpConn.ConnectionString = string.Format("Data Source={0};Initial Catalog={1};User={2};Password={3};MultipleActiveResultSets=True",
                       txtDBServer.Text.Trim(), "master", txtUserName.Text, txtPassword.Text);
                tmpConn.Open();
                if (CheckDatabaseExists(tmpConn))
                {
                    DialogUtils.ShowMessage("Kết nối thành công");
                    btnOK.Enabled = true;
                }
                else
                {
                    if (DialogUtils.ShowYesNo("CSDL bạn muốn kết nối không tồn tại\nBạn có muốn tạo CSDL mới hay không") == DialogResult.Yes)
                    {
                        if (!File.Exists(Application.StartupPath + "\\" + "db.bin"))
                        {
                            DialogUtils.ShowError("File db.bin không tồn tại!");
                            return;
                        }
                        if (!Directory.Exists(txtFolder.Text))
                        {
                            try
                            {
                                Directory.CreateDirectory(txtFolder.Text);
                            }
                            catch
                            {
                                DialogUtils.ShowError("Thư mục chứa CSDL không tồn tại!");
                                return;
                            }
                        }
                        if (CreateDatabase(tmpConn))
                        {
                            DialogUtils.ShowMessage("CSDL đã tạo thành công!");
                            btnOK.Enabled = true;
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                DialogUtils.ShowError("Lỗi.\nChi tiết lỗi: " + exc.Message);
            }
        }

        private void btnQuitApplication_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private bool CreateDatabase(SqlConnection tmpConn)
        {

            string sqlCreateDBQuery;
            sqlCreateDBQuery = string.Format(@"CREATE DATABASE [{0}] ON  PRIMARY 
                                               ( NAME = N'{0}', FILENAME = N'{1}\{0}.mdf' , SIZE = 8448KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
                                               LOG ON 
                                               ( NAME = N'{0}_log', FILENAME = N'{1}\{0}_log.LDF' , SIZE = 4672KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)", txtDBName.Text, txtFolder.Text);
            SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, tmpConn);
            try
            {
                myCommand.ExecuteNonQuery();
                tmpConn.ChangeDatabase(txtDBName.Text);
                sqlCreateDBQuery = ReadFileBinary("db.bin");
                myCommand = new SqlCommand(sqlCreateDBQuery, tmpConn);
                myCommand.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception("Lỗi tạo CSDL! Chi tiết: " + ex.Message);
            }
        }

        private bool CheckDatabaseExists(SqlConnection tmpConn)
        {
            string sqlCreateDBQuery;
            bool rs = false;
            try
            {
                if (chkIs2005.Checked)
                    sqlCreateDBQuery = string.Format("SELECT count(*) FROM master.dbo.sysdatabases WHERE Name = '{0}'", txtDBName.Text);
                else
                    sqlCreateDBQuery = string.Format("SELECT count(*) FROM sys.databases WHERE Name = '{0}'", txtDBName.Text);
                var sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn);
                int databaseID = (int)sqlCmd.ExecuteScalar();
                return rs = databaseID > 0;
            }
            catch (Exception ex)
            {
                throw new Exception("Lỗi kết nối server! Chi tiết: " + ex.Message);
            }
        }

        private void txtPath_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            if (fd.ShowDialog() == DialogResult.OK)
            {
                txtFolder.Text = fd.SelectedPath;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void changedText(object sender, EventArgs e)
        {
            btnOK.Enabled = false;
        }
    }
}
